﻿<%@ WebHandler Language="C#" Class="RbApsPlanDownSendHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Collections;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;

//Description: 热表排产下发回收处理程序
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:zhangrj
//create Date:2024-08-13
public class RbApsPlanDownSendHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    uLMSDispatchIBusiness uMESDispatchbusiness = uMESBusinessFactory.instance.GetuLMSDispatchObject();
    uLMSCommonBusiness commonBusiness = new uLMSCommonBusiness();
    RbContainerBusiness rbBusiness = new RbContainerBusiness();
    RbApsPlanDownSendBusiness rbDownSendBusiness = new RbApsPlanDownSendBusiness();
    string rbFactoryID = System.Configuration.ConfigurationManager.AppSettings["RBFactoryID"].ToString(); //热表ID
    string toAppID_RB = System.Configuration.ConfigurationManager.AppSettings["ToAppID_RB"].ToString(); //数据中心推送目的ID（热表）

    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            if (m_UserInfo == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "登录过期，请重新登录" }));
                return;
            }
            switch (action)
            {
                case "GetApsPlanListByPage": //获取排产下发列表数据（分页）
                    GetApsPlanListByPage(context);
                    break;
                case "GetApsPlanDetailList": //获取排产明细
                    GetApsPlanDetailList(context);
                    break;
                case "SaveApsPlanSendToDis": //保存排产下发
                    SaveApsPlanSendToDis(context);
                    break;
                case "SaveApsPlanRecall": //保存排产回收
                    SaveApsPlanRecall(context);
                    break;
                case "ReSendDispatchToDC": //重新推送报废的派工数据到数据中心
                    ReSendDispatchToDC(context);
                    break;
                case "ExportApsPlanData": //导出排产下发回收数据
                    ExportApsPlanData(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            uMESProcessResult result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    /// <summary>
    /// 导出排产下发回收数据
    /// </summary>
    /// <param name="context"></param>
    public void ExportApsPlanData(HttpContext context)
    {
        Dictionary<string, string> dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["params"].ToString());
        DataTable dtAps = DatabaseHelper.Query_ReturnDatTable(GetApsPlanSendSql(dic, true));
        if (dtAps.Rows.Count == 0)
        {
            uMESProcessResult result = new uMESProcessResult();
            result.Result = false;
            result.Message = "暂无数据可导出";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        byte[] bytes = uLMS_CommonFunction.DataTableExportToExcel(dtAps);
        context.Response.Clear();
        context.Response.Buffer = true;
        context.Response.ClearHeaders();
        context.Response.ClearContent();
        context.Response.ContentType = "application/vnd.ms-excel";
        context.Response.AddHeader("fileDownload", "1");
        context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}{1}.xls", context.Server.UrlEncode("热表排产下发数据导出"), DateTime.Now.ToString("yyyyMMddHHmmssffff")));
        context.Response.AddHeader("Content-Length", bytes.Length.ToString());
        context.Response.AddHeader("Content-Type", "UTF-8");
        context.Response.Charset = "UTF-8";
        context.Response.ContentEncoding = Encoding.UTF8;
        context.Response.BinaryWrite(bytes);
        context.Response.Flush();
        context.Response.Close();
    }

    /// <summary>
    /// 保存排产回收
    /// </summary>
    /// <param name="context"></param>
    public void SaveApsPlanRecall(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        DataTable dtContainer = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        if (dtContainer.Rows.Count == 0)
        {
            result.Result = false; result.Message = "未选择批次";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        StringBuilder sqlBl = new StringBuilder();
        ArrayList sqlList = new ArrayList();
        string updateApsDetailSql = @"UPDATE apsplandetail2 ad SET ad.status = '0', ad.lastchangedate = SYSDATE, ad.recycledate = SYSDATE, ad.recycleemp = '{0}' WHERE ad.apsplandetailid = '{1}'";
        string updateStepDisSql = @"UPDATE containerstepdispatch2 csd SET csd.isuse = 1 WHERE csd.containerid = '{0}' AND csd.stepinfoid = '{1}' AND csd.isuse = 0";
        string updateSpecDisSql = @"UPDATE containerstepdispatch csd SET csd.isuse = 1 WHERE csd.containerid = '{0}' AND csd.workflowstepid = '{1}' AND csd.isuse = 0";
        string selectApsDetailSql = @"SELECT Distinct ad.apsplandetailid,ad.workflowstepid,ad.qty,ad.stepinfoid,ad.starttime,ad.endtime,ad.resourceid,ad.workcenterid,ad.teamid,csd.containerstepdispatchid
                                        FROM apsplandetail2 ad 
                                        LEFT JOIN containerstepdispatch2 csd ON csd.containerid = ad.containerid AND csd.stepinfoid = ad.stepinfoid AND csd.isuse = 0
                                        WHERE ad.containerid = '{0}' AND ad.isuse = 0 AND ad.status = '1'
                                        AND NOT EXISTS(SELECT 1 FROM containerstepworkreport2 csw WHERE csw.containerid = ad.containerid AND csw.stepinfoid = ad.stepinfoid AND csw.isuse = 0)
                                        ORDER BY ad.workflowstepid,ad.stepinfoid";
        /*查询工序的派工ID*/
        string selectSpecDisSql = "SELECT csd.containerstepdispatchid FROM containerstepdispatch csd WHERE csd.containerid = '{0}' AND csd.isuse = 0";
        /*查询工步是否有报工数据*/
        string selectStepReportSql = "SELECT 1 FROM containerstepworkreport2 csw WHERE csw.containerid = '{0}' AND csw.isuse = 0";
        /*查询工步是否已经领工*/
        string selectStepRecSql = @"SELECT 1 FROM containerstepdispatch2 csd WHERE csd.containerid = '{0}' AND csd.isuse = 0 
                                    AND (csd.recvdate IS NOT NULL OR csd.recvemployeeid IS NOT NULL)";
        /*查询工序是否已推送至工控网（做临时限制，后续回收放在工控网）*/
        string selectSpecSendSql = @"SELECT 1 FROM containercurrentinfo c
                                    LEFT JOIN containerstepdispatch csd ON csd.containerid = c.containerid AND csd.isuse = 0
                                    LEFT JOIN sync_tablechangerecord_rb st ON st.tablename = UPPER('containerstepdispatch') AND st.uniquecolvalue = csd.containerstepdispatchid
                                    WHERE c.containerid = '{0}' AND st.businessid IS NOT NULL";
        /*查询批次是否已接收*/
        string selectShipSql = @"SELECT 1 FROM containercurrentinfo c
                                LEFT JOIN containersubcontainer csc ON csc.subcontainerid = c.containerid
                                LEFT JOIN containershiprecord csr ON csr.containerid = csc.containerid
                                LEFT JOIN containershiprecordstep csrd ON csrd.containershiprecordid = csr.containershiprecordid 
                                LEFT JOIN workflowstep ws ON ws.workflowstepid = csrd.workflowstepid
                                WHERE c.containerid = '{0}' AND  csc.workflowstepname = ws.workflowstepname AND csr.toacceptdate IS NOT NULL AND csr.isuse = 0
                                UNION ALL
                                SELECT 1 FROM rbordercontainerreceive rc WHERE rc.containerid = '{0}' AND rc.receivedate IS NOT NULL";
        foreach (DataRow drCon in dtContainer.Rows)
        {
            //if (DatabaseHelper.GetSingle(string.Format(selectShipSql, drCon["containerid"].ToString())) != null) //如果批次已经接收，再判断是否推送工控网
            //{
            //    if (DatabaseHelper.GetSingle(string.Format(selectSpecSendSql, drCon["containerid"].ToString(), toAppID_RB)) == null)
            //    {
            //        result.Result = false;
            //        result.Message = "批次下发数据未推送至工控网，无法回收";
            //        break;
            //    }
            //}
            if (DatabaseHelper.GetSingle(string.Format(selectStepRecSql, drCon["containerid"].ToString())) != null)
            {
                result.Result = false;
                result.Message = "批次存在工步领工，无法回收";
                break;
            }
            if (DatabaseHelper.GetSingle(string.Format(selectStepReportSql, drCon["containerid"].ToString())) != null)
            {
                result.Result = false;
                result.Message = "批次存在工步报工，无法回收";
                break;
            }
            DataTable dtApsDetail = DatabaseHelper.Query_ReturnDatTable(string.Format(selectApsDetailSql, drCon["containerid"].ToString()));//获取未下发的工步
            foreach (DataRow item in dtApsDetail.Rows)
            {
                sqlList.Add(string.Format(updateApsDetailSql, m_UserInfo.EmployeeID, item["apsplandetailid"].ToString()));//将排产明细置为未下发
                sqlList.Add(string.Format(updateStepDisSql, drCon["containerid"].ToString(), item["stepinfoid"].ToString()));//将工步派工置为无效
                sqlList.Add(string.Format(updateSpecDisSql, drCon["containerid"].ToString(), item["workflowstepid"].ToString()));//将工序派工置为无效
            }
            //添加撤销的派工数据推送到数据中心
            sqlList.AddRange(rbBusiness.InsertTableChangeRecord_RB(dtApsDetail.AsDataView().ToTable(true, "containerstepdispatchid"), "containerstepdispatch2", "containerstepdispatchid", 2));
            DataTable dtDis = DatabaseHelper.Query_ReturnDatTable(string.Format(selectSpecDisSql, drCon["containerid"].ToString()));
            sqlList.AddRange(rbBusiness.InsertTableChangeRecord_RB(dtDis, "containerstepdispatch", "containerstepdispatchid", 2));
            //删除旧推送记录
            sqlList.Add(string.Format("DELETE sync_tablechangerecord st WHERE (st.tablename = UPPER('containercurrentinfo') OR st.tablename = UPPER('container')) AND st.uniquecolvalue = '{0}'", drCon["containerid"].ToString()));
        }
        if (result.Result)
        {
            DatabaseHelper.ExecuteSqlTran(sqlList);
            result.Message = "回收成功";
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 重新推送报废的派工数据到数据中心
    /// </summary>
    /// <param name="context"></param>
    private void ReSendDispatchToDC(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "执行成功！" };
        DataTable dtContainer = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        if (dtContainer.Rows.Count == 0)
        {
            result.Result = false; result.Message = "未选择批次";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        string disSql = @"SELECT csd.containerstepdispatchid,COUNT(st.uniquecolvalue) sendcount,'containerstepdispatch2' tablename
                    FROM containerstepdispatch2 csd 
                    LEFT JOIN sync_tablechangerecord_rb st ON st.tablename = UPPER('containerstepdispatch2') AND st.uniquecolvalue = csd.containerstepdispatchid
                    WHERE csd.containerid = '{0}' AND csd.isuse = 1
                    GROUP BY csd.containerstepdispatchid
                    
                    UNION ALL
                    
                    SELECT csd.containerstepdispatchid,COUNT(st.uniquecolvalue) sendcount, 'containerstepdispatch' tablename
                    FROM containerstepdispatch csd 
                    LEFT JOIN sync_tablechangerecord_rb st ON st.tablename = UPPER('containerstepdispatch') AND st.uniquecolvalue = csd.containerstepdispatchid
                    WHERE csd.containerid = '{0}' AND csd.isuse = 1
                    GROUP BY csd.containerstepdispatchid"; //批次所有的报废的工步\工序派工记录
        ArrayList sqlList = new ArrayList();
        foreach (DataRow item in dtContainer.Rows)
        {
            DataTable dtDis = DatabaseHelper.Query_ReturnDatTable(string.Format(disSql, item["containerid"].ToString()));
            if (dtDis.Rows.Count == 0)
            {
                continue;
            }
            if (dtDis.Select("sendcount > 0").Length > 0)//查出已推送的派工
            {
                DataTable dtSendDis = dtDis.Select("sendcount > 0").CopyToDataTable();
                foreach (DataRow drDis in dtSendDis.Rows)
                {
                    /*将推送记录置为未推送，让服务重新推送*/
                    sqlList.Add(string.Format(@"UPDATE sync_tablechangerecord_rb st SET st.ismeshandle = 0 
                                    WHERE st.tablename = UPPER('{0}') AND st.uniquecolvalue = '{1}'", drDis["tablename"].ToString(), drDis["containerstepdispatchid"].ToString()));
                }
            }
            if (dtDis.Select("sendcount = 0 AND tablename = 'containerstepdispatch'").Length > 0)//查出未推送的工序派工
            {
                DataTable dtUnSendDis = dtDis.Select("sendcount = 0 AND tablename = 'containerstepdispatch'").CopyToDataTable();
                if (dtUnSendDis.Rows.Count > 0)
                {
                    sqlList.AddRange(commonBusiness.InsertSyncTableChangeRecode(dtUnSendDis, "containerstepdispatch", "containerstepdispatchid", toAppID_RB, 1, false));
                }
            }
            if (dtDis.Select("sendcount = 0 AND tablename = 'containerstepdispatch2'").Length > 0)//查出未推送的工步派工
            {
                DataTable dtUnSendDis2 = dtDis.Select("sendcount = 0 AND tablename = 'containerstepdispatch2'").CopyToDataTable();
                if (dtUnSendDis2.Rows.Count > 0)
                {
                    sqlList.AddRange(commonBusiness.InsertSyncTableChangeRecode(dtUnSendDis2, "containerstepdispatch2", "containerstepdispatchid", toAppID_RB, 1, false));
                }
            }
        }
        if (sqlList.Count > 0)
        {
            DatabaseHelper.ExecuteSqlTran(sqlList);
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 保存排产下发
    /// </summary>
    /// <param name="context"></param>
    public void SaveApsPlanSendToDis(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        DataTable dtContainer = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        if (dtContainer.Rows.Count == 0)
        {
            result.Result = false; result.Message = "未选择批次";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        DataTable fcAttr = commonBusiness.GetFatoryAttributes(rbFactoryID);
        DataRow[] dataAttr = fcAttr.Select("USERATTRIBUTENAME='转工接收自动下发'");
        string isValidPd = "";
        if (dataAttr.Length > 0)
        {
            isValidPd = dataAttr[0]["ATTRIBUTEVALUE"].ToString();
        }
        string isQtySamesql = @"SELECT 1 FROM containercurrentinfo c
                        LEFT JOIN apsplandetail2 ap ON ap.containerid = c.containerid
                        WHERE c.containerid = '{0}' AND ap.qty != c.qty"; //验证数量是否相等
        string isWorkflowSamesql = @"SELECT 1 FROM containercurrentinfo c
                        WHERE c.containerid = '{0}' AND c.workflowid = '{1}'"; //验证工艺是否相等
        string isExistWTsql = @"SELECT ap.workcenterid,ap.teamid FROM apsplandetail2 ap WHERE ap.containerid = '{0}' AND ap.isuse = 0"; //验证排产工区班组是否为空
        string isWorkReport = @"SELECT 1 FROM containerstepworkreport2 csw WHERE csw.containerid = '{0}' AND csw.isuse = 0";//验证是否报工
        string msg = string.Empty;
        foreach (DataRow item in dtContainer.Rows)
        {
            /*验证批次是否已经暂停*/
            if (commonBusiness.JudeContainerHold(item["containerid"].ToString(), ref msg))
            {
                result.Result = false;
                result.Message = string.Format("批次：{0}已暂停，暂停原因：{1}，请联系调度人员处理！", item["containername"].ToString(), msg);
                break;
            }
            /*验证数量是否一致*/
            if (DatabaseHelper.GetSingle(string.Format(isQtySamesql, item["containerid"].ToString())) != null)
            {
                result.Result = false;
                result.Message = string.Format("批次：{0}在制数和排产数不一致，请重新排产！", item["containername"].ToString());
                break;
            }
            /*验证在制工艺与排产工艺是否一致*/
            if (DatabaseHelper.GetSingle(string.Format(isWorkflowSamesql, item["containerid"].ToString(), item["apsworkflowid"].ToString())) == null)
            {
                result.Result = false;
                result.Message = string.Format("批次：{0}在制工艺与排产工艺不一致，请重新排产！", item["containername"].ToString());
                break;
            }
            /*验证是否存在工步报工*/
            if (DatabaseHelper.GetSingle(string.Format(isWorkReport, item["containerid"].ToString())) != null)
            {
                result.Result = false;
                result.Message = string.Format("批次：{0}已存在工步报工，无法下发！", item["containername"].ToString());
                break;
            }
            /*验证排产的工区班组是否为空*/
            DataTable dtWt = DatabaseHelper.Query_ReturnDatTable(string.Format(isExistWTsql, item["containerid"].ToString()));
            if (dtWt.AsEnumerable().Where(p => string.IsNullOrWhiteSpace(p["workcenterid"].ToString()) || string.IsNullOrWhiteSpace(p["teamid"].ToString())).Count() > 0)
            {
                result.Result = false;
                result.Message = string.Format("批次：{0}排产结果存在工区班组为空的数据，无法下发！", item["containername"].ToString());
                break;
            }
            /*验证特殊过程工序*/
            SpecialReportValidDTO srvDto = rbBusiness.ValidSpecialCourseSpecReport(item["containerid"].ToString());
            if (!srvDto.IsValid)
            {
                result.Result = false;
                result.Message = srvDto.Message;
                break;
            }
            /*验证是否齐套（配置了验证齐套并且批次是转工工序开的批次）*/
            if (isValidPd == "是" && !string.IsNullOrWhiteSpace(item["facontainername"].ToString()))
            {
                if (!rbDownSendBusiness.IsValidApsProducePrepData(item["facontainername"].ToString(), item["faworkflowstepname"].ToString()))
                {
                    result.Result = false;
                    result.Message = string.Format("主卡：{0}的工序：{1}未齐套", item["facontainername"].ToString(), item["faworkflowstepname"].ToString());
                    break;
                }
            }
        }
        if (result.Result)
        {
            result = rbDownSendBusiness.RbApsDownSendAndDispatch(dtContainer.AsDataView().ToTable(true, "containerid", "qty"), m_UserInfo);
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 是否不存在工序派工
    /// </summary>
    /// <param name="containerID"></param>
    /// <param name="workflowstepID"></param>
    /// <returns></returns>
    private bool IsNotExistStepDisInfo(string containerID, string workflowstepID)
    {
        string sql = string.Format("SELECT 1 FROM containerstepdispatch csd WHERE csd.containerid = '{0}' AND csd.workflowstepid = '{1}' AND csd.isuse = 0", containerID, workflowstepID);
        if (DatabaseHelper.GetSingle(sql) != null)
        {
            return false;
        }
        return true;
    }

    /// <summary>
    /// 获取排产列表（分页）
    /// </summary>
    /// <param name="context"></param>
    public void GetApsPlanListByPage(HttpContext context)
    {
        Dictionary<string, string> dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["params"].ToString());
        uMESPagingDataDTO pageDto = new uMESPagingDataDTO();
        pageDto.CurrentPageIndex = int.Parse(dic["pageIndex"]);
        pageDto.PageSize = int.Parse(dic["pageSize"]);
        pageDto.strSQL = GetApsPlanSendSql(dic);
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(pageDto);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取排产下发回收查询SQL
    /// </summary>
    /// <param name="dic">查询参数</param>
    /// <param name="isChineseCol">是否中文列名</param>
    /// <returns></returns>
    private string GetApsPlanSendSql(Dictionary<string, string> dic, bool isChineseCol = false)
    {
        StringBuilder sql = new StringBuilder();
        sql.Append(@"SELECT Distinct cci.containername,cci.containerid,cci.mfgordername,cci.qty,fc.containername facontainername,fc.containerid facontainerid,cci.workflowstepname,
                        ai.starttime,ai.endtime,ai.apsplaninfoid,w.workflowid apsworkflowid,wb.workflowname || ':' || w.workflowrevision workflowinfo,csc.workflowstepname faworkflowstepname,
                        fap.starttime shipstarttime,fap.endtime shipendtime");
        if (isChineseCol)
        {
            sql.Clear();
            sql.Append(@"SELECT Distinct cci.mfgordername 订单号,cci.containername 批次号,wb.workflowname || ':' || w.workflowrevision 排产工艺信息,
                        fc.containername 主制批次,cci.workflowstepname 在制工序,cci.qty 在制数,
                        ai.starttime 计划开始时间,ai.endtime 计划结束时间,
                        fap.starttime 转工计划开始时间,fap.endtime 转工计划结束时间");
        }
        sql.AppendFormat(@"
                        FROM apsplaninfo ai 
                        LEFT JOIN containercurrentinfo cci ON cci.containerid = ai.containerid
                        LEFT JOIN workflow w ON w.workflowid = ai.workflowid
                        LEFT JOIN workflowbase wb ON wb.workflowbaseid = w.workflowbaseid
                        LEFT JOIN ( 
                                  SELECT csc1.subcontainerid,csc1.containerid,csc1.workflowstepname FROM containersubcontainer csc1  GROUP BY csc1.subcontainerid,csc1.containerid,csc1.workflowstepname
                        ) csc ON csc.subcontainerid = cci.containerid
                        LEFT JOIN container fc ON fc.containerid = csc.containerid --查询主制批次     
                        LEFT JOIN apsplandetail fap ON fap.containerid = fc.containerid AND fap.workflowstepname = csc.workflowstepname AND fap.status = '3'
                        WHERE cci.originalfactoryid = '{0}' AND ai.isuse = 0 AND cci.isinstore = 0 AND cci.containerstatus = 1 AND DECODE(fc.containerid,NULL,1,fc.status) = 1
                        ", rbFactoryID);
        if (dic.ContainsKey("MfgOrderName") && !string.IsNullOrWhiteSpace(dic["MfgOrderName"]))
        {
            sql.AppendFormat(" AND cci.mfgordername = '{0}'", dic["MfgOrderName"]);
        }
        if (dic.ContainsKey("ProductName") && !string.IsNullOrWhiteSpace(dic["ProductName"]))
        {
            sql.AppendFormat(" AND cci.productname LIKE '%{0}%'", dic["ProductName"]);
        }
        if (dic.ContainsKey("ContainerName") && !string.IsNullOrWhiteSpace(dic["ContainerName"]))
        {
            sql.AppendFormat(" AND cci.ContainerName LIKE '%{0}%'", dic["ContainerName"]);
        }
        //排产开始日期
        if (dic.ContainsKey("PlanStartTime1") && !string.IsNullOrWhiteSpace(dic["PlanStartTime1"]))
        {

            sql.AppendFormat(" AND ai.starttime >= to_date('{0} {1}','yyyy-mm-dd hh24:mi:ss')", dic["PlanStartTime1"], "00:00:00");
        }
        if (dic.ContainsKey("PlanStartTime2") && !string.IsNullOrWhiteSpace(dic["PlanStartTime2"]))
        {
            sql.AppendFormat(" AND ai.starttime <= to_date('{0} {1}','yyyy-mm-dd hh24:mi:ss')", dic["PlanStartTime2"], "23:59:59");
        }
        //排产结束日期
        if (dic.ContainsKey("PlanEndTime1") && !string.IsNullOrWhiteSpace(dic["PlanEndTime1"]))
        {
            sql.AppendFormat(" AND ai.endtime >= to_date('{0} {1}','yyyy-mm-dd hh24:mi:ss')", dic["PlanEndTime1"], "00:00:00");
        }
        if (dic.ContainsKey("PlanEndTime2") && !string.IsNullOrWhiteSpace(dic["PlanEndTime2"]))
        {
            sql.AppendFormat(" AND ai.endtime <= to_date('{0} {1}','yyyy-mm-dd hh24:mi:ss')", dic["PlanEndTime2"], "23:59:59");
        }
        //状态
        if (dic.ContainsKey("Status") && !string.IsNullOrWhiteSpace(dic["Status"]))
        {
            sql.AppendFormat(" AND EXISTS (SELECT 1 FROM apsplandetail2 ap WHERE ap.apsplaninfoid = ai.apsplaninfoid AND ap.isuse = 0 AND ap.status = '{0}')", dic["Status"]);
        }
        sql.AppendLine(" ORDER BY cci.mfgordername, cci.containername");
        return sql.ToString();
    }

    /// <summary>
    /// 获取工步排产明细
    /// </summary>
    public void GetApsPlanDetailList(HttpContext context)
    {
        string apsId = context.Request["apsID"].ToString();
        string sql = string.Format(@"SELECT ad.stepinfodesc,ad.stepinfono,ad.starttime,ad.endtime,ad.resstarttime,ad.resendtime,r.description resourcedesc,wc.workcentername,t.teamname,
                                    csd.createdate disdate,st.createtime recordtime,st.sendtime,st.businessid
                                    FROM apsplandetail2 ad 
                                    LEFT JOIN resourcedef r ON r.resourceid = ad.resourceid
                                    LEFT JOIN stepinfo s ON s.stepinfoid = ad.stepinfoid
                                    LEFT JOIN workcenter wc ON wc.workcenterid = ad.workcenterid
                                    LEFT JOIN team t ON t.teamid = ad.teamid
                                    LEFT JOIN containerstepdispatch2 csd ON csd.containerid = ad.containerid AND csd.stepinfoid = ad.stepinfoid AND csd.isuse = 0
                                    LEFT JOIN sync_tablechangerecord_rb st ON st.tablename = UPPER('containerstepdispatch2') AND st.uniquecolvalue = csd.containerstepdispatchid
                                    WHERE ad.apsplaninfoid = '{0}' AND ad.status = '{1}' AND ad.isuse = 0
                                    ORDER BY s.stepseq", apsId, context.Request["status"].ToString());
        //uMESProcessResult result = new uMESProcessResult() { Result = true };
        //result.DBTable = DatabaseHelper.Query_ReturnDatTable(sql);
        //context.Response.Write(JsonConvert.SerializeObject(result));
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
        context.Response.Write(JsonConvert.SerializeObject(dt));
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}